/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  EquipListActivity.java   
 * @Package com.jiyi.activity.owner   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-9-8 上午10:59:58   
 * @version V1.0     
 */
package com.jiyi.activity.new_maintenance;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jiyi.adapter.DividerItemDecoration;
import com.jiyi.adapter.recyclerview.CommonAdapter;
import com.jiyi.adapter.recyclerview.base.ViewHolder;
import com.jiyi.adapter.recyclerview.wrapper.EmptyWrapper;
import com.jiyi.adapter.recyclerview.wrapper.HeaderAndFooterWrapper;
import com.jiyi.bean.owner.BuildEquipBean;
import com.jiyi.bean.owner.FloorBean;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.event.BuildListEvent;
import com.jiyi.inteface.ClearEditTextInterface;
import com.jiyi.inteface.WebApi;
import com.jiyi.widget.ClearEditText;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @ClassName: EquipListFragment
 * @Description:TODO(设备列表)
 * @author: HYM
 * @date: 2017-9-8 上午10:59:58
 * 
 */
public class EquipListFragment extends Fragment {

	@BindView(R.id.etSearch)
	ClearEditText etSearch;
	@BindView(R.id.mainList)
	RecyclerView mainList;

	EmptyWrapper adapter;
	LayoutInflater inflater;
	private List<BuildEquipBean> dataList = new ArrayList<BuildEquipBean>();
	private String company_id;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_equip_list, container,
				false);
		ButterKnife.bind(this, view);
		this.inflater = inflater;
		init();
		EventBus.getDefault().register(this);
		return view;
	}
	

	private void init() {
		getIntentData();
		initViewState();
		setAdapter();
		getData(null);
	}
	
	@Subscribe
	public void onBuildListEvent(BuildListEvent buildListEvent)
	{
		getData(null);
	}
	
	@Override
	public void onDestroy() {
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}

	private void getIntentData() {
		company_id = getArguments().getString("company_id");
	}

	private void getData(String keyword) {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("company_id", company_id);
		if (!TextUtils.isEmpty(keyword)) {
			params.put("keyword", keyword);
		}

		VolleyRequest.StringRequestPost(getContext(),
				WebApi.MAINTENANCE_OWNER_EQUIP_LIST, "", params,
				new StringInterface(getContext()) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								List<BuildEquipBean> temp = new Gson()
										.fromJson(
												data,
												new TypeToken<List<BuildEquipBean>>() {
												}.getType());
								dataList.clear();
								dataList.addAll(temp);
								adapter.notifyDataSetChanged();
							} 
							else if (status.equals("404") && info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg("尚未登录或该用户在其他地方登录，请重新登录！");
								//清除环信登录
								UserHelp.getInstance().clearUser(AppBase.Context, true);
								return;
							}
							else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
						}
					}

					@Override
					public void stringError(VolleyError error) {
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}

	private void setAdapter() {

		// 设置布局管理器
		mainList.setLayoutManager(new LinearLayoutManager(getContext()));
		mainList.addItemDecoration(new DividerItemDecoration(getContext(),
				DividerItemDecoration.VERTICAL_LIST, null));
		// 初始化适配器
		CommonAdapter mCommonAdapter = new CommonAdapter<BuildEquipBean>(
				getContext(), R.layout.item_equip_list, dataList) {
			@Override
			protected void convert(final ViewHolder holder,
					final BuildEquipBean t, final int position) {
				holder.setText(R.id.tvBuildName, t.getBuilding());
				holder.setText(R.id.tvLayoutNum, t.getFloor_num() + "");
				holder.setText(R.id.tvEquipNum, t.getEquip_num() + "");
				if (t.getIsExtend()) {
					holder.setVisible(R.id.llChildBuild, true);
					holder.setOnClickListener(R.id.llMoreChild,
							new OnClickListener() {

								@Override
								public void onClick(View v) {
									t.setIsExtend(false);
									adapter.notifyItemChanged(position);
								}
							});
				} else {
					holder.setVisible(R.id.llChildBuild, false);
					holder.setOnClickListener(R.id.llMoreChild,
							new OnClickListener() {

								@Override
								public void onClick(View v) {
									holder.setVisible(R.id.llChildBuild,
											true);
									getChildData(position-1, t.getId());
								}
							});
				}

				holder.setChildEquipAdapter(R.id.childList, t.getBuilds());
			}
		};

		HeaderAndFooterWrapper mHeaderAndFooterWrapper = new HeaderAndFooterWrapper(
				mCommonAdapter);
		View headView = inflater.inflate(R.layout.item_equip_list_head,
				mainList, false);
		headView.setTag("head");
		mHeaderAndFooterWrapper.addHeaderView(headView);

		adapter = new EmptyWrapper(mHeaderAndFooterWrapper);
		adapter.setEmptyView(R.layout.empty_view);

		mainList.setAdapter(adapter);
		adapter.notifyDataSetChanged();
		Log.e("dfsfds    ", mainList.getAdapter().getItemCount() + "");
	}

	private void initViewState() {
		// 设置输入法的搜索事件
		etSearch.setOnEditorActionListener(new OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH
						|| actionId == EditorInfo.IME_ACTION_DONE) {
					InputMethodManager imm = (InputMethodManager) v
							.getContext().getSystemService(
									Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

					Log.e("onEditorAction  ", "   done ");
					search();
					return true;
				}
				return false;
			}
		});
		etSearch.setClearEditTextInterface(new ClearEditTextInterface() {

			@Override
			public void onClear() {
				getData(null);
			}
		});
	}

	void search() {
		getData(etSearch.getText().toString());
	}

	void getChildData(final int position, String buildId) {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("build_id", buildId);

		VolleyRequest.StringRequestPost(getContext(),
				WebApi.MAINTENANCE_OWNER_BUILD_LAYOUT_LIST, "", params,
				new StringInterface(getContext()) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								List<FloorBean> temp = new Gson().fromJson(
										data, new TypeToken<List<FloorBean>>() {
										}.getType());
								dataList.get(position).getBuilds().clear();
								dataList.get(position).getBuilds().addAll(temp);
								dataList.get(position).setIsExtend(true);
								adapter.notifyItemChanged(position+1);
							} 
							else if (status.equals("404") && info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg("尚未登录或该用户在其他地方登录，请重新登录！");
								//清除环信登录
								UserHelp.getInstance().clearUser(AppBase.Context, true);
								return;
							}
							else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
						}
					}

					@Override
					public void stringError(VolleyError error) {
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}

}
